<template>
  <div class="import">
    <div class="app-container">
      <el-card shadow="always" :body-style="{ padding: '20px' }">
        <template #header>
          <span>批量导入员工</span>
        </template>
        <UploadExcel
          :on-success="handleSuccess"
          :before-upload="beforeUpload"
        />
      </el-card>
    </div>
  </div>
</template>

<script>
import { formatExcelDate } from '@/utils/index'
import { addportEmployees } from '@/api/employees'
export default {
  methods: {
    beforeUpload (file) {
      const isLt1M = file.size / 1024 / 1024 < 2

      if (isLt1M) {
        return true
      }

      this.$message({
        message: '导入的excel文件不能大于2M',
        type: 'warning'
      })
      return false
    },
    async handleSuccess ({ results, header }) {
      console.log(results, header)
      // this.tableData = results
      // this.tableHeader = header
      const enResults = this.transformResults(results)
      await addportEmployees(enResults)
      this.$router.back()
      this.$message.success('导入成功')
    },
    transformResults (results) {
      // 映射表
      const userMap = {
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '手机号': 'mobile',
        '姓名': 'username',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }
      const newResults = []
      results.forEach(item => {
        const enUser = {}
        for (const znkey in item) {
          const enkey = userMap[znkey]
          if (enkey === 'timeOfEntry' || enkey === 'correctionTime') {
            enUser[enkey] = formatExcelDate(item[znkey], '-')
          } else {
            enUser[enkey] = item[znkey]
          }
        }
        newResults.push(enUser)
      })
      return newResults
    }
  }

}
</script>

<style lang="scss" scoped>
</style>
